import prisma from '../../utils/prisma'
import { hashPassword } from '../../utils//auth'

export default defineEventHandler(async (event: any) => {
  try {
    const body = await readBody(event)
    const { username, password, email } = body
    
    if (!username || !password || !email) {
      throw createError({
        statusCode: 400,
        statusMessage: '用户名、密码和邮箱不能为空'
      })
    }
    
    // 检查用户是否已存在
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          { username },
          { email }
        ]
      }
    })
    
    if (existingUser) {
      throw createError({
        statusCode: 409,
        statusMessage: '用户名或邮箱已存在'
      })
    }
    
    // 加密密码
    const hashedPassword = await hashPassword(password)
    
    // 创建用户
    const user = await prisma.user.create({
      data: {
        username,
        password: hashedPassword,
        email
      }
    })
    
    return {
      code: 201,
      message: '注册成功',
      data: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    }
    
  } catch (error: any) {
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '内部服务器错误'
    })
  }
})